<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <el-col>
        <el-button type="primary">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 卡片 -->
    <el-card>
      <!-- 表格区域 -->
      <el-table :data="roleList" border stripe style="width: 100%">
        <!-- 扩展列 -->
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <!-- 通过vf -->
            <el-row
              class="btbottom vcenter"
              :class="{ bttop: i1 === 0 }"
              v-for="(level1, i1) in row.children"
              :key="level1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRights(row, level1.id)">{{
                  level1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 方式1.传字符串 -->
                <!-- <el-row :class="i2!==0?'bttop': ''"> -->
                <!-- 方式2.传数组 -->
                <!-- <el-row :class="[i2!==0?'bttop': '']"> -->
                <!-- 方式3.传对象 -->
                <!-- <el-row :class="{'bttop':i2!==0}"> -->
                <el-row
                  class="vcenter"
                  :class="{ bttop: i2 !== 0 }"
                  v-for="(level2, i2) in level1.children"
                  :key="level2.id"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRights(row, level2.id)"
                      >{{ level2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="level3 in level2.children"
                      :key="level3.id"
                      closable
                      @close="deleteRights(row, level3.id)"
                      >{{ level3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="50%"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showRightsDialog(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
    >
      <el-tree
        :data="rightsList"
        :props="{ label: 'authName' }"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="setRights"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      setRightsDialogVisible: false,
      rightsList: [], // 所有的权限
      defKeys: []
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },
    deleteRights (row, rightId) {
      const roleId = row.id
      // 提示是否删除，通过elmecon
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async action => {
          // 发请求
          const { data: res } = await this.$http.delete(
            `roles/${roleId}/rights/${rightId}`
          )
          // 刷新列表
          // 方式1，重新获取整个列表的数据
          //   this.getRoleList()
          // 方式2，获取这一行的权限数据
          row.children = res.data
          // 提示成功，通过elme
          this.$message({
            message: '操作成功',
            type: 'success',
            showClose: true,
            duration: 3000
          })
        })
        .catch(() => {})
    },
    async showRightsDialog (role) {
      this.roleId = role.id
      this.defKeys = []
      this.setRightsDialogVisible = true
      // 获取所用的权限，为显示树组件做准备
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsList = res.data
      // 用递归，多传数据
      this.getLeafKeys(role, this.defKeys)
      this.setRightsDialogVisible = true
    },
    // 方式1.不用递归
    // const rights = role.children
    // rights.forEach(level1 => {
    //   level1.children.forEach(level2 => {
    //     level2.children.forEach(level3 => {
    //       this.defKeys.push(level3.id)
    //     })
    //   })
    // }),
    // 方式2.1.用递归,简化版本
    // this.getLeafKeys(role)
    // getLeafKeys (item) {
    //   if (!item.children) {
    //     this.defKeys.push(item.id)
    //   } else {
    //     item.children.forEach(subItem => {
    //       this.getLeafKeys(subItem)
    //     })
    //   }
    // },
    getLeafKeys (item, arr) {
      if (!item.children) {
        arr.push(item.id)
      } else {
        item.children.forEach(subItem => {
          this.getLeafKeys(subItem, arr)
        })
      }
    },
    async setRights () {
      // 获取数据
      const rids = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ]
      console.log(rids)
      // 发请求
      await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: rids.join(',')
      })
      // 刷新列表
      this.getRoleList()
      // 提示
      this.$message({
        message: '操作成功',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      // 关闭对话框
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bttop {
  border-top: 1px solid #eee;
}
.btbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  // 垂直居中
  align-items: center;
  // 水平居中
  // justify-content: center;
}
</style>
